//
//  YouTubeMediaShareCommunity.m
//  MediaShareBB
//
//  Created by Artak Gevorgyan on 5/23/13.
//  Copyright (c) 2013 InnoriseEntertainment. All rights reserved.
//

#import "AppDelegate.h"
#import "YouTubeMediaShareCommunity.h"
#import "MediaShareData.h"
#import "MediaShareBBUtilityMethods.h"

#import "GTLQueryYouTube.h"
#import "GTLYouTubeVideo.h"
#import "GTLYouTubeVideoSnippet.h"
#import "GTLYouTubeVideoStatus.h"
#import "GTLServiceYouTube.h"
#import "GTLYouTubeConstants.h"

NSString* const kKeychainItemNameYouTube = @"Matit: YouTube";

@interface YouTubeMediaShareCommunity()
{
	NSString* _clientId;
	NSString* _clientSecret;
	MediaShareData* _sharedMediaData;
	GTLServiceTicket* _uploadFileTicket;
	GTMOAuth2ViewControllerTouch* _signInController;
	BOOL _isAuthorized;
    NSString* _sharedMedialink;
}

@end

@implementation YouTubeMediaShareCommunity

-(id) init {
	self = [super init];
	if (self) {
		super.name = @"YouTube";
		super.communityType = MEDIA_SHARE_COMMUNITY_YOUTUBE;
		super.supportedMediaTypes = [[NSArray alloc] initWithObjects:
									 [NSNumber numberWithInt:VIDEO_MEDIA_TYPE], nil];
	}
	return self;
}

#pragma mark - Superclass methods

// Superclass method
-(NSString*) description {
	NSString* d = @"YouTube description";
	return d;
}

// Superclass method
-(void) configureWithCredentials:(NSDictionary*) credentials {
	_clientId = [credentials valueForKey:@"clientId"];
	_clientSecret = [credentials valueForKey:@"clientSecret"];
	GTMOAuth2Authentication *auth =
	[GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemNameYouTube
														  clientID:_clientId
													  clientSecret:_clientSecret];
	if ([auth canAuthorize]) {
		[self isAuthorizedWithAuthentication:auth];
	}
}

// Superclass method
-(void) login {
	if (!_isAuthorized) {
        SEL finishedSelector = @selector(viewController:finishedWithAuth:error:);
        GTMOAuth2ViewControllerTouch* authViewController = [[GTMOAuth2ViewControllerTouch alloc]
																	   initWithScope:kGTLAuthScopeYouTubeUpload
																		    clientID:_clientId
																		clientSecret:_clientSecret
																	keychainItemName:kKeychainItemNameYouTube
																			delegate:self
																	finishedSelector:finishedSelector];
		_signInController = authViewController;
		_signInController.delegate = self;
        [self presentViewController:authViewController];
    } else {
        if ([MediaShareBBUtilityMethods isObject:super.delegate
							  respondsToSelector:@selector(loginSuccess)]) {
			[super.delegate loginSuccess];
		}
    }
}

//Superclass method
-(void) loginWithAnotherUser {
    [GTMOAuth2ViewControllerTouch removeAuthFromKeychainForName:kKeychainItemNameYouTube];
    [[self youTubeService] setAuthorizer:nil];
    _isAuthorized = NO;
    SEL finishedSelector = @selector(viewController:finishedWithAuth:error:);
    GTMOAuth2ViewControllerTouch* authViewController = [[GTMOAuth2ViewControllerTouch alloc]
                                                        initWithScope:kGTLAuthScopeYouTubeUpload
                                                        clientID:_clientId
                                                        clientSecret:_clientSecret
                                                        keychainItemName:kKeychainItemNameYouTube
                                                        delegate:self
                                                        finishedSelector:finishedSelector];
    _signInController = authViewController;
    _signInController.delegate = self;
    [self presentViewController:authViewController];
}

//Superclass method
-(NSString*) getUserName {
    GTMOAuth2Authentication* auth = self.youTubeService.authorizer;
    BOOL isSignedIn = auth.canAuthorize;
    if (isSignedIn) {
        return auth.userEmail;
    } else {
        return nil;
    }
}

-(NSString*) sharedMediaLink {
    return _sharedMedialink;
}

// Superclass method
-(void) shareMedia:(MediaShareData*) data {
	if ([super isValidMediaType:data.mediaType]) {
		_sharedMediaData = data;
		if ([MediaShareBBUtilityMethods isObject:super.delegate
							  respondsToSelector:@selector(willSharingMedia:through:)]) {
			[super.delegate willSharingMedia:_sharedMediaData
									 through:self];
		}
		[self upload];
	} else {
		NSLog(@"%s: Unsupported media type:%d", __PRETTY_FUNCTION__, data.mediaType);
	}
}

#pragma mark - GTMOAuth2ViewControllerTouchDelegate methods

-(void) signInProcessCanceled {
	AppDelegate* app = [UIApplication sharedApplication].delegate;
	UIViewController* controller = app.window.rootViewController;
//	UIViewController* controller = [super.delegate targetViewController];
	[controller dismissViewControllerAnimated:YES completion:nil];
	[_signInController cancelSigningIn];
	if ([MediaShareBBUtilityMethods isObject:super.delegate
						  respondsToSelector:@selector(loginCanceled)]) {
		[super.delegate loginCanceled];
	}
}

#pragma mark - Private methods

-(void) isAuthorizedWithAuthentication:(GTMOAuth2Authentication*) auth {
    [[self youTubeService] setAuthorizer:auth];
	_isAuthorized = YES;
}

-(void) presentViewController:(GTMOAuth2ViewControllerTouch*) vc {
	if ([MediaShareBBUtilityMethods isObject:super.delegate
						  respondsToSelector:@selector(targetViewController)] ) {
		AppDelegate* app = [UIApplication sharedApplication].delegate;
		UIViewController* controller = app.window.rootViewController;
//		UIViewController* controller = [super.delegate targetViewController];
		if (IPAD) {
			vc.modalPresentationStyle = UIModalPresentationFormSheet;
		}
		[controller presentViewController:vc animated:YES completion:nil];
	}
}

-(void) viewController:(GTMOAuth2ViewControllerTouch*) viewController
	  finishedWithAuth:(GTMOAuth2Authentication*) auth
                 error:(NSError*) error {
	AppDelegate* app = [UIApplication sharedApplication].delegate;
	UIViewController* controller = app.window.rootViewController;
//	UIViewController* controller = [super.delegate targetViewController];
	[controller dismissViewControllerAnimated:YES completion:nil];

	if (error) {
		if ([error code] != kGTMOAuth2ErrorWindowClosed) {
			NSLog(@"%s: Unresolved sign in error: %@ %@", __PRETTY_FUNCTION__,
				  error, [error userInfo]);
		}
		if ([MediaShareBBUtilityMethods isObject:super.delegate
							  respondsToSelector:@selector(loginFailedWithError:)]) {
			[super.delegate loginFailedWithError:error];
		}
	} else {
		NSLog(@"%s: Success login", __PRETTY_FUNCTION__);
		[self isAuthorizedWithAuthentication:auth];
		if ([MediaShareBBUtilityMethods isObject:super.delegate
							  respondsToSelector:@selector(loginSuccess)]) {
			[super.delegate loginSuccess];
		}
	}
}

-(GTLServiceYouTube*) youTubeService {
    static GTLServiceYouTube* service;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        service = [[GTLServiceYouTube alloc] init];
        service.shouldFetchNextPages = YES;
        service.retryEnabled = YES;
    });
    return service;
}

-(void) upload {
    // Status.
    GTLYouTubeVideoStatus* status = [GTLYouTubeVideoStatus object];
    status.privacyStatus = @"public";

    // Snippet.
    GTLYouTubeVideoSnippet* snippet = [GTLYouTubeVideoSnippet object];
    snippet.title = _sharedMediaData.fileName;
    snippet.tags = [NSArray arrayWithObject:_sharedMediaData.youtubeTags];
    snippet.descriptionProperty = _sharedMediaData.description;
    snippet.categoryId = @"28";
	
    GTLYouTubeVideo* video = [GTLYouTubeVideo object];
    video.status = status;
    video.snippet = snippet;

    NSFileHandle* fileHandle = [NSFileHandle fileHandleForReadingAtPath:_sharedMediaData.path];
    if (fileHandle) {
        NSString* mimeType = @"video/mp4";
        GTLUploadParameters* uploadParameters =
		[GTLUploadParameters uploadParametersWithData:_sharedMediaData.data
											 MIMEType:mimeType];

        uploadParameters.uploadLocationURL = nil;

        GTLQueryYouTube* query = [GTLQueryYouTube queryForVideosInsertWithObject:video
                                                                            part:@"snippet,status"
                                                                uploadParameters:uploadParameters];
        GTLServiceYouTube* service = self.youTubeService;
        _uploadFileTicket = [service executeQuery:query
                                completionHandler:^(GTLServiceTicket* ticket,
                                                    GTLYouTubeVideo* uploadedVideo,
                                                    NSError* error) {
                                    // Callback
                                    _uploadFileTicket = nil;
                                    if (error == nil) {
										NSLog(@"success !");
                                        _sharedMedialink = [NSString stringWithFormat:@"http://youtu.be/%@", uploadedVideo.identifier];
										if ([MediaShareBBUtilityMethods isObject:super.delegate
															  respondsToSelector:@selector(didFinishSharingMedia:through:)]) {
											[super.delegate didFinishSharingMedia:_sharedMediaData
																		  through:self];
										}
                                    } else {
										NSLog(@"Failed !");
										if ([MediaShareBBUtilityMethods isObject:super.delegate
															  respondsToSelector:@selector(didFailedSharingMedia:through:withError:)]) {
											[super.delegate didFailedSharingMedia:_sharedMediaData
																		  through:self
																		withError:nil];
										}
                                    }
								}];
    }
}

@end
